package com.zx.auth.block.component;

import com.zx.core.wrapper.ObjectWrapper;
import com.zx.feign.client.SystemClient;
import com.zx.feign.client.dto.GetLoginUserResponseDTO;
import com.zx.security.common.model.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * description: 根据用户获取用户信息和用户权限 <br>
 * create: 2024-08-22 13:30
 *
 * @author zhou  xun
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
    private final SystemClient systemClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ObjectWrapper<GetLoginUserResponseDTO> result = systemClient.getUserInfoByLoginCredential(username);
        // 检查用户是否存在
        if (result.verifyFail()) {
            String errorMsg = result.getMsg();
            log.warn("Failed to load user by credential: {}, error: {}", username, errorMsg);
            // 注意：这里不区分"用户不存在"和"密码错误"的情况
            // 因为Spring Security的DaoAuthenticationProvider会将UsernameNotFoundException
            // 转换为BadCredentialsException，导致上层无法区分具体错误类型
            // 具体的错误类型区分在LoginService中通过其他方式实现
            throw new UsernameNotFoundException(errorMsg);
        }
        GetLoginUserResponseDTO getLoginUserResponseDTO = result.getData();
        if (getLoginUserResponseDTO == null) {
            log.warn("No user found for credential: {}", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        return new LoginUser(getLoginUserResponseDTO.id(), getLoginUserResponseDTO.username(), getLoginUserResponseDTO.password(), getLoginUserResponseDTO.roles(), getLoginUserResponseDTO.permissions(), getLoginUserResponseDTO.status(), getLoginUserResponseDTO.tenantId(), getLoginUserResponseDTO.tenantName());
    }
}